package io.tim.timongodb.util.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;  
  
   
public class Java2XML {  
      
    Map<String, String> books = new HashMap<String, String>();
    public Java2XML() {
    	/*this.books.put("1","唐诗三百首");
    	this.books.put("2","Think in Java");
    	this.books.put("3","神雕侠侣");
    	this.books.put("4","葵花宝典");*/
    	
    }
    
    public void BuildXMLDoc() throws IOException, JDOMException {     
        // 创建根节点 并设置它的属性 ;     
        Element root = new Element("books").setAttribute("count", "4");     
        // 将根节点添加到文档中；     
        Document Doc = new Document(root);     
        Iterator iter = books.entrySet().iterator();
        while (iter.hasNext()) {
        	Map.Entry<String, String> entry = (Entry<String, String>) iter.next();
        	// 创建节点 book;     
            Element elements = new Element("book");       
            // 给 book 节点添加子节点并赋值；     
            elements.addContent(new Element("id").setText(entry.getKey()));    
            elements.addContent(new Element("name").setText(entry.getValue()));    
            //    
            root.addContent(elements);   
        }
        
        // 输出 books.xml 文件；    
        // 使xml文件 缩进效果  
        Format format = Format.getPrettyFormat();  
        XMLOutputter XMLOut = new XMLOutputter(format);  
        XMLOut.output(Doc, new FileOutputStream("e:/books.xml"));  
    }   
    public static void main(String[] args) {    
       try {    
           Java2XML j2x = new Java2XML();    
           System.out.println("正在生成 books.xml 文件...");    
           j2x.BuildXMLDoc();    
       } catch (Exception e) {    
           e.printStackTrace();    
       }    
       System.out.println("e:/books.xml 文件已生成");  
    }    
}  